import sys
import time
from datetime import datetime
from os import system

import psutil
import schedule


class ArgsProcessor:
    def __init__(self, argv) -> None:
        self.argc: int = len(argv)
        self.argv: list = argv

        self.target: str = ""
        self.timer: str | int = ""
        self.action: str = ""

    def cmd_args(self) -> None:
        i_target = self.argv.index('--debug')
        if i_target < self.argc - 1:
            main_debug()
            exit(0)


        i_target = self.argv.index('--target')
        if i_target < self.argc - 1:
            self.target = self.argv[i_target + 1]
        else:
            print("[error] Invalid parameter [--target]: cannot get target file after parameter [--target]")
        i_timer = self.argv.index('--timer')
        if i_timer < self.argc - 1:
            self.timer = int(self.argv[i_timer + 1])
        else:
            print("[error] Invalid parameter [--timer]: cannot get target file after parameter [--timer]")
        i_action = self.argv.index('--action')
        if i_action < self.argc - 1:
            self.action = self.argv[i_action + 1]
        else:
            print("[error] Invalid parameter [--action]: cannot get target file after parameter [--action]")

        print("[Init] Command parameters mode...")
        return


def main() -> bool:
    pids: list[int] = psutil.pids()
    # process_names: list[str] = []
    for pid in pids:
        p = psutil.Process(pid)
        if p.name() == a.target:
            print(f"[info][{datetime.now().strftime('%y%m%d_%H%M%S')}] Target process still alive")
            return True
        else:
            continue
    #  遍历过后仍未找到匹配的pname，尝试重试启动
    print(f"[info][{datetime.now().strftime('%y%m%d_%H%M%S')}] Target process died, executing action...")
    system("start cmd /c " + a.action)
    return False


def main_debug() -> None:
    pids: list[int] = psutil.pids()
    process_names: list[str] = []
    for pid in pids:
        p = psutil.Process(pid)
        process_names.append(p.name())
    print(process_names)


if __name__ == "__main__":
    print("[ALPHA RELEASE] This is a python-based process watch and restart tool.")
    a = ArgsProcessor(sys.argv)
    a.cmd_args()

    schedule.run_pending()
    schedule.every(a.timer).minutes.do(main)
    print(f'[Init] Program will check [{a.target}] if is alive every {a.timer} minutes')

    while True:
        schedule.run_pending()
        time.sleep(1)
